﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;

namespace TestCheckMemcached
{
    public class Common
    {
        /// <summary>
        /// 同步连接
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public void MemcachedConnect(Server server)
        {
            IPAddress ipa = IPAddress.Parse(server.Host);
            IPEndPoint ipep = new IPEndPoint(ipa, server.Port);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ipep);
            socket.Send(Encoding.ASCII.GetBytes("stats\r\n"));
            string result = "";
            byte[] recvBytes = new byte[1024];
            int bytes;
            bytes = socket.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
            result += Encoding.ASCII.GetString(recvBytes, 0, bytes);
            socket.Close();
        }

        /// <summary>
        /// 启动远程Memcached服务
        /// </summary>
        /// <param name="server">服务IP</param>
        /// <param name="User">域\用户名</param>
        /// <param name="Password">密码</param>
        public void ResterNetWorkMemcachedService(Server server, string User, string Password)
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;

            process.Start();

            process.StandardInput.AutoFlush = true;

            string cmd = string.Format("net use \\\\{0}\\ipc$ {1} /user:{2}", "10.0.50.27", "Ifca1234", "dm_ifca\\cfyong");

            process.StandardInput.WriteLine(cmd);
            Console.WriteLine(cmd);

            cmd = string.Format("sc \\\\{0} stop \"memcached Server\"", server.Host);
            process.StandardInput.WriteLine(cmd);
            Console.WriteLine(cmd);

            //process.StandardInput.WriteLine("sc \\\\10.0.50.27 start W32Time");
            //Console.WriteLine("sc \\\\10.0.50.27 start W32Time");

            process.StandardInput.Close();
            Console.Write(process.StandardOutput.ReadToEnd());
            Console.ReadLine();
        }
    }
}
